/* eslint-disable @typescript-eslint/no-unused-vars */
import React from 'react';
import { BottomAction } from '@/components';
import { Button, message, Form, Radio, Popover, DatePicker, Icon, Select, Checkbox, Popconfirm, Tooltip } from 'antd';
import pageTabUtil from '@/utils/pageTabUtil';
import { defaultFormatResult, useRequest } from '@/hooks';
import { getLeavingProveList } from '@/pages/TurnoverSetting/LeaveSetting/services';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { PrintModal } from '@/pages/WorkFlow/OnboardAndLeave/QuitManagement/QuitHandover/components/PrintModal';
import { history } from 'umi'
import moment from 'moment';
import { CollapseHeader, VacationTable, LimitInput, PayrollComputationTable } from '../components';
import styles from './index.less';
import {
    completeHandover,
    queryVocationList,
    getColumnlist,
    getLeavePayroll,
    generateLeavePayroll
} from '../../service';
import { LEAVE_STATUS_OBJ } from '../../dictionary';

const { MonthPicker } = DatePicker;
const { Option } = Select;

function PersonnelHandover({ form, data, dimissionOrderId, employeeCode, dutyName, ...rest }) {
    const [submitLoading, setSubmitLoading] = React.useState();
    const [vacationLoading2, setVacationLoading2] = React.useState(true);
    const [vocationList, setVocationList] = React.useState([]);
    const [vacationOptions, setVacationOptions] = React.useState({});
    const [templateContent, setTemplateContent] = React.useState('');
    const [settlementTimeType, setSettlementTimeType] = React.useState(data.matterDetail[0].settlementTimeType ?? 1);
    const [leavePayrollData, setLeavePayrollData] = React.useState();
    const [printModalVisible, setPrintModalVisible] = React.useState(false);
    const { getFieldDecorator, validateFields } = form;
    const { hasFormChange, initialForm } = useFormChange(form);
    // 获取假期数据
    const params = {
        // companyCode: 'ORG15540490989436999',
        companyCode: data?.dimissionOrderVO.companyCode,
        // employeeCodes: ['oa1420013715800248321'],
        employeeCodes: [employeeCode],
        pageNo: 1,
        pageSize: 50
    };
    const { run: getVocationList, loading: vacationLoading } = useRequest(() => queryVocationList(params), {
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data: data3, msg } = res;
                if (code === 10000) {
                    if (data3.rows[0]?.vocationList.length > 0) {
                        const list = data3.rows[0]?.vocationList
                            .filter(item => vacationOptions[item.leaveCode].openState === '1')
                            .map(item => {
                                // remainDuration:剩余时长， discountingDurationUpperLimit：折现天数
                                // 接口给的都是分钟，展示要分小时、天，传给后台分钟
                                // 一天8小时制
                                const temp = {
                                    holidayName: vacationOptions[item.leaveCode].leaveName,
                                    // remainDuration:
                                    //     item.leaveCode === 'CommonYear'
                                    //         ? (item.value / (8 * 60)).toFixed(2)
                                    //         : Number(item.value),
                                    remainDuration: Number(item.value),
                                    durationType: 1,
                                    holidayCode: item.leaveCode
                                };
                                return temp;
                            });
                        setVocationList([...list]);
                    }
                    initialForm();
                    setVacationLoading2(false);
                    return data3;
                }
                setVacationLoading2(false);
                message.error(msg);
            }
            setVacationLoading2(false);
            return undefined;
        }
    });
    // 获取假期类型选项
    // useRequest(() => getColumnlist('ORG15540490989436999'), {
    useRequest(() => getColumnlist(data?.dimissionOrderVO.companyCode), {
        formatResult: res => {
            if (res) {
                const { code, data: data2, msg } = res;
                if (code === 10000) {
                    const options = {};
                    for (let i = 0, len = data2.length; i < len; i += 1) {
                        // options[data2[i].leaveCode] = data2[i].leaveName;
                        options[data2[i].leaveCode] = { leaveName: data2[i].leaveName, openState: data2[i].openState };
                    }
                    setVacationOptions(options);
                    getVocationList();
                    setVacationLoading2(false);
                    return options;
                }
                setVacationLoading2(false);
                message.error(msg);
            }
            setVacationLoading2(false);
            return undefined;
        }
    });
    // 获取离职模版列表
    const { data: leaveTemplateList = [], loading: leaveTemplateListLoading } = useRequest(getLeavingProveList, {
        formatResult: res => {
            if (res) {
                const { code, data: templatelist, msg } = res;
                if (code === 10000) {
                    setTemplateContent(templatelist[0].templateContent);
                    return templatelist;
                }
                message.error(msg);
            }
            return undefined;
        }
    });
    const printDetailData = {
        companyName: data?.dimissionOrderVO.companyName,
        employeeName: data?.dimissionOrderVO.employeeName,
        idNumber: data?.dimissionOrderVO.idCard,
        dutyName: data?.dimissionOrderVO.dutyName,
        entryDate: data?.dimissionOrderVO.entryDate,
        dimissionDate: data?.dimissionOrderVO.finalDimissionDate
    };
    // 获取薪资总额
    const params2 = {
        employeeCode,
        organizationCode: data?.dimissionOrderVO.companyCode
    };
    const { loading: leavePayrollLoading } = useRequest(() => getLeavePayroll(params2), {
        formatResult: res => {
            if (res) {
                const { code, data: data2, msg } = res;
                if (code === 10000) {
                    setLeavePayrollData(data2);
                } else {
                    message.error(msg);
                }
            }
            return undefined;
        }
    });
    // 刷新薪资
    const param3 = {
        employeeCode,
        settleTimeType: settlementTimeType,
        organizationCode: data?.dimissionOrderVO.companyCode,
        compensation: data?.dimissionOrderVO.compensation
    };
    const { run: generateLeavePayrollRun, loading: generateLeavePayrollLoading } = useRequest(
        () => generateLeavePayroll(param3),
        {
            manual: true,
            formatResult: res => {
                if (res) {
                    const { code, data: data3, msg } = res;
                    if (code === 10000) {
                        setLeavePayrollData(data3);
                        message.success('已获取最新的薪资数据');
                    } else {
                        message.error(msg);
                    }
                }
                return undefined;
            }
        }
    );
    const handleSubmit = () => {
        const { matterDetail, dimissionOrderVO, handoverSettings } = data;
        const handlerDetail = matterDetail?.find(m => m.handoverType === LEAVE_STATUS_OBJ.PERSONNEL_HANDOVER);
        if (!handlerDetail) {
            message.error('未查询到人事交接详情');
            return;
        }
        validateFields(async (err, values) => {
            const len = vocationList.length;
            if (len > 0) {
                for (let i = 0; i < len; i += 1) {
                    if (!vocationList[i].dealType) {
                        message.warning('请完成假期结算处理方式', 3);
                        break;
                    }
                }
            }
            if (err) {
                return;
            }
            const submitData = {};
            if (len > 0) {
                submitData.handoverHolidays = vocationList.map(item => {
                    const newItem = item;
                    newItem.discountingDurationUpperLimit = item.discountingDurationUpperLimit
                        ? item.discountingDurationUpperLimit * (item.holidayCode === 'CommonYear' ? 60 * 8 : 60)
                        : 0;
                    return newItem;
                });
            }
            const { hrHandoverTypes } = handoverSettings;
            if (hrHandoverTypes.includes(2) && leaveTemplateList.length > 0) {
                submitData.dimissionTemplateId = values.dimissionTemplateId;
            }
            if (hrHandoverTypes.includes(3)) {
                submitData.stopPaymentPfsi = values.stopPaymentPfsi.format(
                    handoverSettings.stopPaymentPfsiType === 1 ? 'YYYY-MM' : 'YYYY-MM-DD'
                );
            }
            if (hrHandoverTypes.includes(4)) {
                submitData.settlementTimeType = values.settlementTimeType;
            }
            if (hrHandoverTypes.includes(5)) {
                submitData.permitRecycleFlag = values.permitRecycleFlag ? 1 : 0;
            }
            try {
                setSubmitLoading(true);
                const { code, msg } = await completeHandover({
                    id: handlerDetail?.id,
                    dimissionOrderId,
                    handoverType: LEAVE_STATUS_OBJ.PERSONNEL_HANDOVER,
                    remark: values.remark,
                    ...submitData
                });
                if (code === 10000) {
                    message.success('提交成功！', 2);
                    history.replace('/office/personnelManagement/onboardAndLeave/leaveManagement/list');
                } else {
                    message.error(msg);
                }

                setSubmitLoading(false);
            } catch (e) {
                setSubmitLoading(false);
            }
        });
    };

    const VacationTableOnchange = (e, index, type) => {
        const arr = [...vocationList];
        if (type === 'dealType') {
            arr[index].dealType = e;
        } else {
            arr[index].discountingDurationUpperLimit = e;
        }
        setVocationList(arr);
    };
    const templateChange = e => {
        for (let i = 0, len = leaveTemplateList.length; i < len; i += 1) {
            if (e === leaveTemplateList[i].id) {
                setTemplateContent(leaveTemplateList[i].templateContent);
            }
        }
    };
    const fullLineLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 }
    };
    return (
        <Form layout="horizontal" {...fullLineLayout}>
            <CollapseHeader title="假期结算">
                <div className={styles.itemBox}>剩余假期结算方式，请与员工沟通确认：</div>
                <VacationTable
                    getFieldDecorator={getFieldDecorator}
                    value={vocationList}
                    onChange={VacationTableOnchange}
                    vacationLoading={vacationLoading || vacationLoading2}
                />
            </CollapseHeader>
            {data.handoverSettings.hrHandoverTypes.includes(4) && (
                <CollapseHeader title="薪资计算">
                    {data.handoverSettings.allowChoiceSalarySettlementTimeFlag === 1 ? (
                        <Form.Item
                            labelCol={{ span: 2 }}
                            label={
                                <span>
                                    结算时间 &nbsp;
                                    <Tooltip title="立即结算为提交后将立刻触发薪资计算流程并在流程结束后发放">
                                        <Icon type="question-circle-o" style={{ color: 'rgba(0,0,0,0.45)' }} />
                                    </Tooltip>
                                </span>
                            }
                        >
                            <div>
                                {getFieldDecorator('settlementTimeType', {
                                    initialValue: data.matterDetail[0].settlementTimeType || 1,
                                    rules: [{ required: true }],
                                    onChange: e => {
                                        setSettlementTimeType(e.target.value);
                                    }
                                })(
                                    <Radio.Group>
                                        <Radio value={1}>随下一个发薪日统一结算</Radio>
                                        <Radio value={2}>立即结算</Radio>
                                    </Radio.Group>
                                )}
                            </div>
                        </Form.Item>
                    ) : (
                        <div className={styles.itemBox}>
                            结算时间：<span className={styles.val}>随下一个发薪日统一结算</span>
                        </div>
                    )}
                    <div className={styles.itemBox}>
                        薪资明细：
                        {settlementTimeType === 2 && (
                            <>
                                <Icon type="exclamation-circle" style={{ color: '#ffa22d' }} theme="filled" />
                                <span style={{ color: '#ffa22d', marginLeft: '4px' }}>请导入绩效系数，并核对无误</span>
                            </>
                        )}
                    </div>
                    <PayrollComputationTable
                        type="personnel"
                        leavePayrollData={leavePayrollData}
                        loading={leavePayrollLoading || generateLeavePayrollLoading}
                        compensation={data?.dimissionOrderVO.compensation}
                        generateLeavePayrollRun={generateLeavePayrollRun}
                        dimissionType={data?.dimissionOrderVO.dimissionType}
                    />
                </CollapseHeader>
            )}
            <CollapseHeader title="其他">
                {/* 公积金/社保停缴月份 .    默认填充离职日期/所在月份 */}
                {data.handoverSettings.hrHandoverTypes.includes(3) && (
                    <Form.Item
                        label={
                            <span>
                                {`公积金/社保停缴${data.handoverSettings.stopPaymentPfsiType === 1 ? '月份' : '日期'}`}
                                &nbsp;
                                {data.handoverSettings.stopPaymentPfsiType === 1 ? (
                                    ''
                                ) : (
                                    <Tooltip title="离职日期为当月 15 号前，则停缴月份为上月；离职日期为当月 15 号（含）以后，则停缴月份为当月">
                                        <Icon type="question-circle-o" style={{ color: 'rgba(0,0,0,0.45)' }} />
                                    </Tooltip>
                                )}
                            </span>
                        }
                    >
                        <div>
                            {getFieldDecorator('stopPaymentPfsi', {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue:
                                    data?.dimissionOrderVO.finalDimissionDate === ''
                                        ? null
                                        : moment(
                                              data?.dimissionOrderVO.finalDimissionDate.slice(
                                                  0,
                                                  data.handoverSettings.stopPaymentPfsiType === 1 ? 7 : 10
                                              )
                                          )
                            })(
                                data.handoverSettings.stopPaymentPfsiType === 1 ? (
                                    <MonthPicker style={{ width: 182, display: 'inline-block' }} />
                                ) : (
                                    <DatePicker style={{ width: 182, display: 'inline-block' }} />
                                )
                            )}
                        </div>
                    </Form.Item>
                )}
                {data.handoverSettings.hrHandoverTypes.includes(2) && (
                    <Form.Item label="离职证明">
                        {leaveTemplateList.length === 0 ? (
                            <span>
                                离职证明模板未配置，请前往【离职设置】完成配置
                                <a>立即配置</a>
                            </span>
                        ) : (
                            <>
                                {getFieldDecorator('dimissionTemplateId', {
                                    initialValue: leaveTemplateList[0]?.id,
                                    onChange: templateChange
                                })(
                                    <Select
                                        style={{ width: 182, display: 'inline-block' }}
                                        loading={leaveTemplateListLoading}
                                    >
                                        {leaveTemplateList.map((item, index) => (
                                            <Option key={item.id} value={item.id}>
                                                {item.templateName}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                                <Icon
                                    type="printer"
                                    onClick={() => setPrintModalVisible(true)}
                                    style={{ marginLeft: '10px', fontSize: '18px' }}
                                />
                            </>
                        )}
                    </Form.Item>
                )}
                {data.handoverSettings.hrHandoverTypes.includes(2) && printModalVisible && (
                    <PrintModal
                        visible={printModalVisible}
                        detailData={printDetailData}
                        templateContent={templateContent}
                        handleCancel={() => {
                            setPrintModalVisible(false);
                        }}
                    />
                )}
                {data.handoverSettings.hrHandoverTypes.includes(5) && (
                    <Form.Item label="外国人准证回收">
                        {getFieldDecorator('permitRecycleFlag', {
                            initialValue: data.matterDetail[0].permitRecycleFlag || 0
                        })(<Checkbox>已回收</Checkbox>)}
                    </Form.Item>
                )}
                <Form.Item label="备注">
                    {getFieldDecorator('remark', {
                        initialValue: data.matterDetail[0].remark
                    })(
                        <LimitInput
                            area
                            autoSize={{ minRows: 3, maxRows: 6 }}
                            placeholder="请填写备注"
                            maxLength={4000}
                        />
                    )}
                </Form.Item>
            </CollapseHeader>
            <BottomAction>
                {hasFormChange() ? (
                    <Popconfirm
                        title={
                            <>
                                当前页面存在改动信息暂未提交，
                                <br />
                                确定离开此页面？
                            </>
                        }
                        arrowPointAtCenter
                        onConfirm={() => pageTabUtil.goBack()}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button style={{ marginRight: 8 }}>取消</Button>
                    </Popconfirm>
                ) : (
                    <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                )}
                {!data.handoverSettings.hrHandoverTypes.includes(4) ||
                (leavePayrollData?.payrollList && leavePayrollData?.payrollList[0]?.encryptTotalAmt) ? (
                    <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                        确定
                    </Button>
                ) : (
                    <Popconfirm
                        title={
                            <>
                                离职人员薪资待计算，
                                <br />
                                确定交接完成？
                            </>
                        }
                        placement="bottomRight"
                        onConfirm={handleSubmit}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button style={{ marginRight: 8 }} type="primary">
                            确定
                        </Button>
                    </Popconfirm>
                )}
            </BottomAction>
        </Form>
    );
}
export default Form.create()(PersonnelHandover);
